﻿using Magicodes.WeiChat.App_Start;
using NLog;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
using Magicodes.WeChat.SDK;
using Magicodes.WeiChat.WeChatHelper.Task;
using System.Web.SessionState;
using System.Web.Hosting;
using Magicodes.Logger;
using Magicodes.Logger.NLog;
using Magicodes.WeiChat.Infrastructure.Events;

namespace Magicodes.WeiChat
{
    public class MvcApplication : System.Web.HttpApplication
    {
        LoggerBase logger = new NLogLogger("GlobalApplication");
        protected void Application_Start()
        {
            //记录托管异常
            AppDomain.CurrentDomain.FirstChanceException += CurrentDomain_FirstChanceException;

            GlobalConfiguration.Configure(WebApiConfig.Register);
            RouteConfig.RegisterRoutes(RouteTable.Routes);

            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            LoggerConfig.Register();
            FilterConfig.RegisterMagicodesFilter();

            BundleConfig.RegisterBundles(BundleTable.Bundles);
            WeChatSDKConfig.RegisterSdkFuncs();
            //设置站内通知
            Magicodes_Notify_Config.Builder();
            //配置任务管理器
            TaskManagerConfig.ConfigTaskManager();
            //配置事件侦听逻辑
            EventListenerConfig.Register();
        }
        protected void Application_PostAuthorizeRequest()
        {
            if (IsWebApiRequest())
            {
                HttpContext.Current.SetSessionStateBehavior(SessionStateBehavior.Required);
            }
        }
        private bool IsWebApiRequest()
        {
            return HttpContext.Current.Request.AppRelativeCurrentExecutionFilePath.StartsWith(WebApiConfig.UrlPrefixRelative);
        }
        protected void Application_Error(object sender, EventArgs e)
        {
            //获取异常
            var lastError = Server.GetLastError().GetBaseException();
            string requestStr = null;
            if (HttpContext.Current != null)
            {
                var context = HttpContext.Current;
                requestStr = string.Format("URL:{1}{0}{2}", Environment.NewLine, context.Request.Url, lastError);
            }
            if (string.IsNullOrEmpty(requestStr))
                logger.Log(LoggerLevels.Error, lastError);
            else
                logger.Log(LoggerLevels.Error, requestStr);
        }

        void CurrentDomain_FirstChanceException(object sender, System.Runtime.ExceptionServices.FirstChanceExceptionEventArgs e)
        {
            //LogManager.GetCurrentClassLogger().Error(e.Exception, "托管代码错误");
            //if (e.Exception.InnerException != null)
            //{
            //    LogManager.GetCurrentClassLogger().Error(e.Exception.InnerException, "托管代码错误");
            //}
        }
    }

}
